from ev import utils
from game.gamesrc.objects.exit import MyExit
from game.gamesrc.objects.lock import Lock

class Door(Lock, MyExit):
    def at_object_creation(self):
        super(Door, self).at_object_creation()
        self.locks.add("traverse:self_attr(is_closed, False)")
        self.db.door_name = "una porta"
        self.db.flags.append('DOOR')

    def return_appearance(self, pobject):
        """
        This is a convenient hook for a 'look'
        command to call.
        """
        if not self.db.is_closed:
            string = super(Door, self).return_appearance(pobject)
            return "%s\n{w%s e' aperta.{n" % (string, self.db.door_name.capitalize())

        string = "{c%s{n" % self.db.door_name.capitalize()
        desc = utils.fill(self.attr("desc"))
        if desc:
            string += "\n %s" % desc
        string += "\n{wE' chiuso%s.{n\n"
        if self.db.is_locked:
            string = string % " a chiave"
        else: string = string % ""
        return string

    def open(self):
        super(Door, self).open()
        if self.db.linkeddoor:
            ldoor = self.search("#%s" % self.db.linkeddoor, global_search=True)
            ldoor.db.is_closed = False
            ldoor.location.msg_contents("%s viene aperta." % self.db.door_name.capitalize())

    def close(self):
        super(Door, self).close()
        if self.db.linkeddoor:
            ldoor = self.search("#%s" % self.db.linkeddoor, global_search=True)
            ldoor.db.is_closed = True
            ldoor.location.msg_contents("%s viene chiusa." % self.db.door_name.capitalize())

    def lock(self):
        super(Door, self).lock()
        if self.db.linkeddoor:
            ldoor = self.search("#%s" % self.db.linkeddoor, global_search=True)
            ldoor.db.is_locked = True
            ldoor.location.msg_contents("La serratura di %s viene chiusa a chiave dall'altra parte." % self.db.door_name)

    def unlock(self):
        super(Door, self).unlock()
        if self.db.linkeddoor:
            ldoor = self.search("#%s" % self.db.linkeddoor, global_search=True)
            ldoor.db.is_locked = False
            ldoor.location.msg_contents("La serratura di %s viene sbloccata dall'altra parte." % self.db.door_name)

    def at_failed_traverse(self, traversing_object):
        """
        This is called if an object fails to traverse this object for some
        reason. It will not be called if the attribute "err_traverse" is defined,
        that attribute will then be echoed back instead as a convenient shortcut.

        (See also hooks at_before_traverse and at_after_traverse).
        """
        traversing_object.msg("%s e' chiusa." % self.db.door_name.capitalize())

        
